package com.lzb.compressmaster.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.lzb.compressmaster.BaseAc;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.adapter.DocumentsAdapter;
import com.lzb.compressmaster.basic.media.MediaInfo;
import com.lzb.compressmaster.databinding.ActivitySearchBinding;
import com.lzb.compressmaster.dialog.AudioPreviewDialog;
import com.lzb.compressmaster.utils.MimeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseAc<ActivitySearchBinding> implements View.OnClickListener, OnItemClickListener {

    public static String keyword;
    private DocumentsAdapter documentsAdapter;
    private List<MediaInfo> searchResults = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        mDataBinding.tvSearchCancel.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivClear.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        documentsAdapter = new DocumentsAdapter();
        mDataBinding.rvFileList.setAdapter(documentsAdapter);
        documentsAdapter.setOnItemClickListener(this);

        // 设置搜索框监听器
        setupSearchListener();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ivClear) {//清空
            clearSearchResults();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        String path = documentsAdapter.getItem(position).getPath();
        if (FileUtils.isDir(path)) {
            Intent intent = new Intent();
            intent.putExtra(Content.path, path);
            setResult(RESULT_OK, intent);
            finish();
        } else if (MimeUtils.isImgMimeType(path)) {
            ImageViewer.load(path)//要加载的图片数据，单张或多张
                    .imageLoader(new GlideImageLoader())// 图片加载器，目前内置的有CoilImageLoader、GlideImageLoader和PicassoImageLoader，也可以自己实现
                    .selection(position)//当前选中位置，默认：0
                    .showIndicator(true)//是否显示指示器，默认不显示
                    .theme(com.king.image.imageviewer.R.style.ImageViewerTheme)//设置主题风格，默认：R.style.ImageViewerTheme
                    .orientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//设置屏幕方向,默认：ActivityInfo.SCREEN_ORIENTATION_BEHIND
                    .start(this);//activity or fragment, 跳转时的共享元素视图
        } else if (MimeUtils.isVideoMimeType(path)) {
            VideoPreviewActivity.sVideoPath = path;
            startActivity(VideoPreviewActivity.class);
        } else if (MimeUtils.isAudioMimeType(path)) {
            showAudioPreviewDialog(path);
        } else {
            gotoPreview(UriUtils.file2Uri(new File(path)));
        }
    }

    @Override
    protected void initData() {
        // 初始化数据，可以在这里预加载一些内容
        mDataBinding.etName.setText(keyword);
        searchFiles();
    }

    private void setupSearchListener() {
        // 监听输入框内容变化
        mDataBinding.etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                if (TextUtils.isEmpty(str)) {
                    mDataBinding.ivClear.setVisibility(View.INVISIBLE);
                } else {
                    mDataBinding.ivClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 监听软键盘搜索按钮
        mDataBinding.etName.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                    (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                keyword = mDataBinding.etName.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    searchFiles();
                } else {
                    ToastUtils.showShort(R.string.please_input_file_name);
                }
                return true;
            }
            return false;
        });
    }

    private void searchFiles() {
        searchResults.clear();

        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//        RxUtil.create(new RxUtil.Callback<Boolean>() {
//
//            @Override
//            public void doBackground(ObservableEmitter<Boolean> emitter) {
                // 从外部存储根目录开始递归搜索
                String rootPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
                searchInDirectory(new File(rootPath), keyword);
//                emitter.onNext(true);
//            }
//
//            @Override
//            public void accept(Boolean result) {
                dismissDialog();
                // 更新UI
                updateSearchResults();
//            }
//        });
            }
        }, 1000);
    }

    private void searchInDirectory(File directory, String keyword) {
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return;
        }

        File[] files = directory.listFiles();
        if (files == null) return;

        for (File file : files) {
            // 检查文件名是否包含关键词（不区分大小写）
            if (file.getName().toLowerCase().contains(keyword.toLowerCase())) {
                searchResults.add(new MediaInfo(
                        file.getPath(),
                        file.getName(),
                        file.length(),
                        FileUtils.getFileLastModified(file),
                        null,
                        null
                ));
            }
            if (file.isDirectory()) {
                // 递归搜索子目录
                searchInDirectory(file, keyword);
            } else {

            }
        }
    }

    private void updateSearchResults() {
        if (searchResults.isEmpty()) {
            mDataBinding.flFileNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvFileList.setVisibility(View.GONE);
        } else {
            mDataBinding.flFileNoData.setVisibility(View.GONE);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            documentsAdapter.setList(searchResults);
        }
    }

    private void clearSearchResults() {
        searchResults.clear();
        mDataBinding.etName.setText("");
        documentsAdapter.setList(searchResults);
        mDataBinding.flFileNoData.setVisibility(View.VISIBLE);
        mDataBinding.rvFileList.setVisibility(View.GONE);
    }

    private void showAudioPreviewDialog(String path) {
        AudioPreviewDialog audioPreviewDialog = new AudioPreviewDialog(mContext);
        audioPreviewDialog.setAudioPath(path);
        audioPreviewDialog.show();
    }

    //跳转到预览应用
    private void gotoPreview(Uri selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(selUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            startActivity(intent);
        } else {
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }
}